package com.wpzf.ndhc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wpzf.common.core.utils.StringUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.ndhc.domain.WpGTYDkjbxxNdDTO;
import com.wpzf.ndhc.domain.WpGTYTbjbxxNd2024;
import com.wpzf.ndhc.domain.WpSjsbDkpwjbbxxNdDTO;
import com.wpzf.ndhc.mapper.WpzfNdhcFxMapper;
import com.wpzf.ndhc.mapper.WpzfNdhcGTYDockMapper;
import com.wpzf.ndhc.service.WpzfNdhcFxService;
import com.wpzf.ndhc.service.WpzfNdhcGTYDockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WpzfNdhcFxServiceImpl implements WpzfNdhcFxService {

    @Autowired
    private WpzfNdhcFxMapper wpzfNdhcFxMapper;

    @Override
    @Transactional
    public Integer saveResult(Map<String, Object> param) {

        Map<String, Object> tbhcjg = wpzfNdhcFxMapper.queryTbhcjg(param);
        if (tbhcjg == null || "0".equals(tbhcjg.get("status") + "")) {
            wpzfNdhcFxMapper.deleteTbhcjg(param);
            wpzfNdhcFxMapper.deleteHftgzmwj(param);
            wpzfNdhcFxMapper.deleteQtpzwh(param);
            wpzfNdhcFxMapper.deleteQtsftgxxydss(param);
            wpzfNdhcFxMapper.deleteQtsfzyg(param);
            wpzfNdhcFxMapper.deleteWfpzwh(param);
            wpzfNdhcFxMapper.deleteWftgzmwj(param);


            param.put("submitdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
            Integer rest = wpzfNdhcFxMapper.saveTbhcjg(param);
            if (rest > 0) {
                List<Map<String, Object>> hftgzmwjList = (List<Map<String, Object>>) param.get("hftgzmwjList");
                if (hftgzmwjList != null && hftgzmwjList.size() > 0) {
                    for (Map<String, Object> map : hftgzmwjList) {
                        wpzfNdhcFxMapper.saveHftgzmwj(map);
                    }
                }
                List<Map<String, Object>> qtpzwhList = (List<Map<String, Object>>) param.get("qtpzwhList");
                if (qtpzwhList != null && qtpzwhList.size() > 0) {
                    for (Map<String, Object> map : qtpzwhList) {
                        wpzfNdhcFxMapper.saveQtpzwh(map);
                    }
                }
                List<Map<String, Object>> qtsftgxxydssList = (List<Map<String, Object>>) param.get("qtsftgxxydssList");
                if (qtsftgxxydssList != null && qtsftgxxydssList.size() > 0) {
                    for (Map<String, Object> map : qtsftgxxydssList) {
                        wpzfNdhcFxMapper.saveQtsftgxxydss(map);
                    }
                }
                List<Map<String, Object>> qtsfzygList = (List<Map<String, Object>>) param.get("qtsfzygList");
                if (qtsfzygList != null && qtsfzygList.size() > 0) {
                    for (Map<String, Object> map : qtsfzygList) {
                        wpzfNdhcFxMapper.saveQtsfzyg(map);
                    }
                }
                List<Map<String, Object>> wfpzwhList = (List<Map<String, Object>>) param.get("wfpzwhList");
                if (wfpzwhList != null && wfpzwhList.size() > 0) {
                    for (Map<String, Object> map : wfpzwhList) {
                        wpzfNdhcFxMapper.saveWfpzwh(map);
                    }
                }
                List<Map<String, Object>> wftgzmwjList = (List<Map<String, Object>>) param.get("wftgzmwjList");
                if (wftgzmwjList != null && wftgzmwjList.size() > 0) {
                    for (Map<String, Object> map : wftgzmwjList) {
                        wpzfNdhcFxMapper.saveWftgzmwj(map);
                    }
                }
            }
            return rest;
        } else if ("1".equals(tbhcjg.get("status") + "")) {
            return -1;
        } else {
            return 0;
        }
    }

    @Override
    public Integer updateHcjgsm(Map<String, Object> param) {
        Integer rest = 0;
        Map<String, Object> hcjgsm = wpzfNdhcFxMapper.getHcjgsm(param);
        if (hcjgsm != null) {
            rest = wpzfNdhcFxMapper.updateHcjgsm(hcjgsm);
        }
        return rest;
    }

    @Override
    public Map<String, Object> queryResult(Map<String, Object> param) {
        Map<String, Object> rest = wpzfNdhcFxMapper.queryTbhcjg(param);
        if (rest != null && rest.size() > 0) {
            List<Map<String, Object>> hftgzmwjList = wpzfNdhcFxMapper.queryHftgzmwj(param);
            List<Map<String, Object>> qtpzwhList = wpzfNdhcFxMapper.queryQtpzwh(param);
            List<Map<String, Object>> qtsftgxxydssList = wpzfNdhcFxMapper.queryQtsftgxxydss(param);
            List<Map<String, Object>> qtsfzygList = wpzfNdhcFxMapper.queryQtsfzyg(param);
            List<Map<String, Object>> wfpzwhList = wpzfNdhcFxMapper.queryWfpzwh(param);
            List<Map<String, Object>> wftgzmwjList = wpzfNdhcFxMapper.queryWftgzmwj(param);
            rest.put("hftgzmwjList", hftgzmwjList);
            rest.put("qtpzwhList", qtpzwhList);
            rest.put("qtsftgxxydssList", qtsftgxxydssList);
            rest.put("qtsfzygList", qtsfzygList);
            rest.put("wfpzwhList", wfpzwhList);
            rest.put("wftgzmwjList", wftgzmwjList);
        }
        return rest;
    }

    @Override
    public Map<String, Object> queryDetails(Map<String, Object> param) {
        Map<String, Object> rest = new HashMap<>();
        String xzqdm = param.get("xzqdm").toString();
        String dkbsm = param.get("dkbsm").toString();
        AjaxResult ajaxResult = getnddkxxbInfo(xzqdm, dkbsm);
        if (ajaxResult.get("code").equals(200)) {
            //国土云推送图斑和地块 先删除再插入 todo 国土云接口数据有问题 tbbsm bsm dkbsm
            JSONObject jsonObject = JSONObject.parseObject(ajaxResult.get("msg").toString());
            JSONObject tbjbxx = jsonObject.getJSONObject("tbjbxx");
            JSONObject dkjbxx = jsonObject.getJSONObject("dkjbxx");
            JSONArray dkpwjbxx = jsonObject.getJSONArray("dkpwjbxx");
            if (tbjbxx != null) {
                WpGTYTbjbxxNd2024 wpGTYTbjbxxNd2024 = JSON.toJavaObject(tbjbxx, WpGTYTbjbxxNd2024.class);
                Map<String, Object> map1 = new HashMap<>();
                map1.put("tbbsm", wpGTYTbjbxxNd2024.getTbbsm());
                map1.put("xzqdm", wpGTYTbjbxxNd2024.getXzqdm());
                //删除原始
                int k = wpzfNdhcFxMapper.deletetbjbxxbytbbsm(map1);
                //插入新增
                k = wpzfNdhcFxMapper.saveGTYTbxxbxjNd2024(wpGTYTbjbxxNd2024);
                if (k > 0) {
                    System.out.println("图斑信息保存成功");
                }
                rest.put("tbjbxx", wpGTYTbjbxxNd2024);
            }
            if (dkjbxx != null) {
                WpGTYDkjbxxNdDTO wpGTYDkjbxxNdDTO = JSON.toJavaObject(dkjbxx, WpGTYDkjbxxNdDTO.class);
                Map<String, Object> map = new HashMap<>();
                map.put("dkbsm", wpGTYDkjbxxNdDTO.getBsm());
                map.put("xzqdm", wpGTYDkjbxxNdDTO.getXzqdm());
                //删除原始 地块 批文
                wpzfNdhcFxMapper.deleteDkjbxxbyBsm(map);
                wpzfNdhcFxMapper.deleteDkpwjbxxbyDkbsm(map);
                //插入新增
                int k = wpzfNdhcFxMapper.saveGTYDkJbxxNd2024(wpGTYDkjbxxNdDTO);
                if (k > 0) {
                    System.out.println("地块信息保存成功");
                }
                rest.put("dkjbxx", wpGTYDkjbxxNdDTO);
            }
            if (dkpwjbxx != null && dkpwjbxx.size() > 0) {
                //批文信息 暂时未处理
                List<WpSjsbDkpwjbbxxNdDTO> wpSjsbDkpwjbbxxNdDTOList = dkpwjbxx.toJavaList(WpSjsbDkpwjbbxxNdDTO.class);
                for (WpSjsbDkpwjbbxxNdDTO wpSjsbDkpwjbbxxNdDTO : wpSjsbDkpwjbbxxNdDTOList) {
                    wpzfNdhcFxMapper.saveGTYDkpwjbbxxNd2024(wpSjsbDkpwjbbxxNdDTO);
                }
                rest.put("dkpwjbxx", wpSjsbDkpwjbbxxNdDTOList);
            }
        }
        return rest;
    }


    public AjaxResult getnddkxxbInfo(String xzqdm, String dkbsm) {
        try {
            String postURL = "";
            String data = "";
            {
                postURL = "https://jg.landcloud.org.cn:8553/webapi/token";
                data = "client_id=web&client_secret=e46232c20609435eba54b7576de935dd&grant_type=password&username=a53e0c14ee900728f36bba014d975982&password=b30c775c48e9ba92ade95e427a5242b0";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            //关闭流
            is.close();
            conn.disconnect();
            String result = new String(datas, 0, datas.length, "utf-8");
            AjaxResult ajaxResult = getNDDxxxb(result, "00gty_wpzf2024_dk", xzqdm, dkbsm); //年度地块信息
            return ajaxResult;
        } catch (Exception ex) {
            return AjaxResult.error("获取国土云地块信息,错误原因:" + ex.getMessage());
        }
    }

    public AjaxResult getNDDxxxb(String str, String ywmb, String xzqdm, String dkbsm) {
        String rest = "";
        try {
            String postURL = "";
            String token = "";
            String token_type = "";
            Map mapType = JSON.parseObject(str, Map.class);
            {
                for (Object obj : mapType.keySet()) {

                    if ((obj + "").equals("access_token")) {
                        token = mapType.get("access_token") + "";
                        token_type = mapType.get("token_type") + "";
                    }
                }
                System.out.println(token);
                //接口地址
                postURL = "https://wp.tianmu.cloud:5443/webapi/api/open/GetWPZFDKInfo";
            }
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            String encoding = com.wpzf.common.core.utils.sign.Base64.encode(str.getBytes());
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8 ");
            conn.setRequestProperty("Authorization", token_type + " " + token);
            //  conn.setRequestProperty("token", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            //获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            //  out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            //String xmbh="210115S120240216LJ00005";

            if (StringUtils.isNotBlank(xzqdm)) {
                //String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\"}";
                String data = "{\"xzqdm\":\"" + xzqdm + "\",\"ywmb\":\"" + ywmb + "\",\"xmbh\":[\"" + dkbsm + "\"]}";
                System.out.println("---------获取地块列表参数------" + data);
                out.write(data);
                out.flush();
                InputStream is = conn.getInputStream();
                int count = 0;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                while ((count = is.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, count);
                }
                byte[] datas = byteArrayOutputStream.toByteArray();

                byteArrayOutputStream.close();
                is.close();
                conn.disconnect();
                rest = new String(datas, 0, datas.length, "utf-8");
                JSONObject obj = JSONObject.parseObject(rest);
                System.out.println(obj.get("data"));
                if (obj.get("data") == null) {
                    rest = data + "获取国土云地块信息为null";
                    return AjaxResult.error(rest);
                } else {
                    String objdata = obj.get("data").toString();
                    JSONObject arr = JSONObject.parseObject(objdata);
                    return AjaxResult.success(objdata);
                }
            } else {
                return AjaxResult.error("获取国土云地块信息,错误原因:参数为空");
            }
        } catch (Exception e) {
            rest = "网络异常，请稍后重试！";
            //writeLog(UtilTool.GetTime_1()+"："+e.getMessage()+"\n");
            return AjaxResult.error("获取国土云地块信息,错误原因:" + e.getMessage());
        }
    }


    @Override
    public List<Map<String, Object>> getVerificationStatsByDistrict(Map<String, Object> param) {
        return wpzfNdhcFxMapper.getVerificationStatsByDistrict();
    }

    @Override
    public List<Map<String, Object>> getVerificationResultInfoByDK(Map<String, Object> param) {
        return wpzfNdhcFxMapper.getVerificationResultInfoByDK();
    }

}
